from util.math.MathUtil import *
from paper.PaperFactory import PaperFactory
from paper.CorrectPaperFactory import CorrectPaperFactory
from util.file.FileHandler import *
import os
import codecs
import getopt,sys
import time

def main(argv):
    arguments =  analyseArgument(argv)
    if type(arguments["answer"]) is str:
        if  type(arguments["output"]) is str:
            correctPapers(arguments)
        else:
            print("Wrong Argument Use Main.py -e <exerciseFile>.txt -a <answerFile>.txt -o GradeFile  to correct papers")
            sys.exit(-1)
    else:
        if type(arguments["range"]) is int  and type(arguments["number"]) is int and type(arguments["output"]) is str:
            createPapers(arguments)
        else:
            print("Wrong Argument Use Main.py -r <the range of number> -n <numbers of expression> to create file")


def analyseArgument(argv):
    try:
        opts,args = getopt.getopt(argv,"o:e:a:r:n:h",["range=","numbers=","answer=","output=","exercise=","help"])
    except getopt.GetoptError:
        print("Illegal Argument!")
        sys.exit(-1)
    range = 10
    number = 10
    judgeAnswer = False
    outputFile = False
    exerciseFile = False
    for opt,arg in opts:
        if opt in ('-h',"-help"):
            print("Main.py -r <the range of number> -n <numbers of expression>")
            sys.exit()
        elif opt in ("-r","-range"):
            range = int(arg)
        elif opt in ("-n","-number"):
            number = int(arg)
        elif opt in ("-o","-output"):
            outputFile = arg
        elif opt in ("-a","-answer"):
            judgeAnswer = arg
        elif opt in ("-e","-exercise"):
            exerciseFile = arg

    return {"range":range,"number":number,"answer":judgeAnswer,"output":outputFile,"exercise":exerciseFile}

def logError(message):
    print("Error: "+message)

def createPapers(args):
    if args["range"] < 1 or args['number'] < 1 :
        logError("the range or number must higher than 0")
        sys.exit(-1)
    outputFilePath = os.getcwd() + "/" + args["output"]
    paperFactory = PaperFactory(args)
    paper = paperFactory.createPaper()
    saveFileContent(outputFilePath,paper)

def correctPapers(args):
    ansFilePath = os.getcwd() + "/" + args["answer"]
    if not os.path.exists(ansFilePath):
        logError(ansFilePath + " do not exists!")
        sys.exit(-1)

    outputFilePath = os.getcwd() + "/" + args["output"]

    correctPaperFactory = CorrectPaperFactory()

    f = codecs.open(ansFilePath,"r","utf8")
    problems = f.readlines()
    for problemStr in  problems:
        if len(problemStr.strip()) < 1:continue
        correctPaperFactory.judgeProblem(problemStr)
    f.close()
    
    of = codecs.open(outputFilePath,"w","utf8")
    cps = correctPaperFactory.getPaperAfterCorrect()
    for line in cps:
        of.write(line)
    of.write("---------------------------\r\n")
    of.write(correctPaperFactory.getResultString())
    of.write("---------------------------\r\n")
    of.close()

if __name__ == "__main__":
    start = time.time() * 1000
    main(sys.argv[1:])
    end = time.time() * 1000
    print("Info: All job done in "+str(round(end-start))+" ms")



